/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-07-06 20:57:49
 * @LastEditTime: 2024-07-27 13:24:40
 * @FilePath: /nest_study/server/src/modules/monitor/online/online.service.ts
 */
import { Injectable } from '@nestjs/common';
import { OnlineListDto } from './dto/index.dto';
import { RedisService } from 'src/modules/redis/redis.service';
import { CacheEnum } from 'src/common/enum/cache';
import { ResultData } from 'src/common/utils/result';
import { PaginationData } from 'src/common/utils';
import { CacheService } from 'src/modules/cache/cache.service';

@Injectable()
export class OnlineService {
  constructor(
    private readonly redisService: RedisService,
    private readonly cacheService: CacheService,
  ) { }

  async findAll(query: OnlineListDto) {
    const keys = await this.redisService.keys(`${CacheEnum.LOGIN_TOKEN_KEY}*`);
    const data = await this.redisService.mget(keys);
    const list = PaginationData({
      list: data,
      size: query.size,
      page: query.page
    }, query).map(item => {
      return {
        tokenId: item.token,
        deptName: item.user.deptName,
        userName: item.username,
        id: item.userId,
        ipaddr: item.ipaddr,
        loginLocation: item.loginLocation,
        browser: item.browser,
        os: item.os,
        loginTime: item.loginTime,
      };
    });
    return ResultData.ok({
      list,
      total: data.length,
      size: query.size,
      page: query.page
    });
  }

  async remove(info: { token: string, id: number }) {
    let { token, id } = info;
    await this.redisService.del(`${CacheEnum.LOGIN_TOKEN_KEY}${token}`);
    await this.cacheService.storeDel(`user_${id}_token`)
    await this.redisService.del(`user_${id}_token`);
    return ResultData.ok();
  }
}
